package lv.solcraft.replication.client;

import javax.sql.DataSource;

import lv.solcraft.replication.client.boot.ClientBootConfig;
import lv.solcraft.replication.common.client.ClientSettings;
import lv.solcraft.replication.common.server.SettingsFacade;

import org.apache.log4j.Logger;
import org.springframework.jdbc.core.JdbcTemplate;

public class ClientConfig {

    private static Logger log = Logger.getLogger(ClientConfig.class);

    private static final String GET_SITE_ID_SQL = "SELECT SITE_ID FROM SCR_SITE";

    private ClientBootConfig config;

    private volatile ClientSettings settings;

    private SettingsFacade settingsFacade;

    private DataSource dataSource;

    private Integer siteId;

    public String getName() {
        return config.getClientName();
    }

    public ClientSettings getSettings() {
        if (settings == null) {
            reloadSettings();
        }
        return settings;
    }

    public void reloadSettings() {
        log.info("Loading settings from server, " + getName());
        settings = settingsFacade.getClientSettings(getServerName());
    }

    public SettingsFacade getSettingsFacade() {
        return settingsFacade;
    }

    public void setSettingsFacade(SettingsFacade settingsFacade) {
        this.settingsFacade = settingsFacade;
    }

    public String getServerName() {
        return config.getServerName();
    }

    private int loadSiteId() {
        log.info("Loading site id, " + getName());
        JdbcTemplate jt = new JdbcTemplate(dataSource);
        return jt.queryForInt(GET_SITE_ID_SQL);
    }

    public DataSource getDataSource() {
        return dataSource;
    }

    public void setDataSource(DataSource dataSource) {
        this.dataSource = dataSource;
    }

    public int getSiteId() {
        if (siteId == null) {
            siteId = new Integer(loadSiteId());
            log.info("Site id is " + siteId + ", " + getName());
        }
        return siteId.intValue();
    }

    public void setSettings(ClientSettings settings) {
        this.settings = settings;
    }

    public void setConfig(ClientBootConfig config) {
        this.config = config;
    }

    public ClientBootConfig getConfig() {
        return config;
    }
}
